package demo1;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Main3 {
    public static void main(String[] args) throws InterruptedException {
        Counter1 counter1=new Counter1();
        Thread t1 =new Thread(()->{
            for (int i=0;i<1_00000;i++) {
                counter1.increase1();
            }
        });
        Thread t2=new Thread(()->{
            for (int i=0;i<1_0000;i++) {
                counter1.increase1();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter1.sum);
    }
}
class Counter1{
    //共享变量
    int sum=0;
    ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock();
    //读锁
    ReentrantReadWriteLock.ReadLock readLock=reentrantReadWriteLock.readLock();
    //写锁
    ReentrantReadWriteLock.WriteLock writeLock=reentrantReadWriteLock.writeLock();
    public void increase1(){
        try {
            readLock.lock();
            sum++;
        } finally {
            readLock.unlock();
        }
    }
    public void increase2(){
        try {
            writeLock.lock();
            sum++;
        } finally {
            writeLock.unlock();
        }
    }
}
